package com.ruoyi.job.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.common.utils.BeanCopyUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.laiwu.domain.bo.SyncConfigBo;
import com.ruoyi.laiwu.domain.vo.SyncConfigVo;
import com.ruoyi.laiwu.service.ISyncConfigService;
import com.ruoyi.laiwu.util.AkskSampleApplication;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class SyncDataHandler {

    private final ISyncConfigService iSyncConfigService;

    @XxlJob("initSync")
    public void initSync(){
        List<SyncConfigVo> syncConfigVos = iSyncConfigService.queryList(new SyncConfigBo());
        for (SyncConfigVo syncConfigVo : syncConfigVos) {
            syncConfigVo.setStatus("not");
            iSyncConfigService.updateByBo(BeanCopyUtils.copy(syncConfigVo, SyncConfigBo.class));
        }
        XxlJobHelper.log("初始化数据");
    }

    @XxlJob("syncHandler")
    public void syncHandler(){
        List<SyncConfigVo> syncConfigVos = iSyncConfigService.queryList(new SyncConfigBo());
        for (SyncConfigVo syncConfigVo : syncConfigVos) {
            if("not".equals(syncConfigVo.getStatus())){
                syncConfigVo.setStatus("syncing");
                iSyncConfigService.updateByBo(BeanCopyUtils.copy(syncConfigVo, SyncConfigBo.class));
                syncTable(syncConfigVo);
            }
        }
    }

    @XxlJob("syncTableHandler")
    public void syncTableHandler(){
        String param = XxlJobHelper.getJobParam();
        String[] split = param.split(StringUtils.SEPARATOR);
        syncTableHandler(split[0],split[1],split[2]);
    }

    public void syncTableHandler(String url,String modelClass,String mapperName){
        int pageNum = 1;
        int pageSize = 100;
        int totalPages = Integer.MAX_VALUE;
        while (pageNum<=totalPages){
            System.out.println(pageNum+"aaaaaa"+totalPages);
            BaseMapper mapper = SpringUtils.getBean(mapperName);
            System.out.println(mapper);
            JSONObject pageData = getPageData(url, pageNum, pageSize);
            System.out.println(pageData);
            totalPages = pageData.getInt("totalPages");
            if (pageNum==1){
                mapper.delete(new QueryWrapper());
            }
            pageNum++;
            pageData.getJSONArray("data").stream().forEach(i -> {
                try {
                    System.out.println(i);
                    System.out.println(modelClass);
                    Object bean = JSONUtil.toBean(JSONUtil.parseObj(i), Class.forName(modelClass));
                    mapper.insert(bean);
                    System.out.println(bean);
                } catch (ClassNotFoundException e) {
                    System.out.println(e);
                }
            });
        }

    }


    @Async
    public void syncTable(SyncConfigVo syncConfigVo){
        syncTableHandler(syncConfigVo.getUrl(), syncConfigVo.getModelClass(), syncConfigVo.getMapperName());
        syncConfigVo.setStatus("finish");
        iSyncConfigService.updateByBo(BeanCopyUtils.copy(syncConfigVo,SyncConfigBo.class));
    }


    private JSONObject getPageData(String url, int pageNum, int pageSize){
        String token = null;
        try {
            token = AkskSampleApplication.getToken();
            System.out.println(token);
        } catch (IOException e) {
            System.out.println(url+"?pageNum="+pageNum+"&pageSize="+pageSize);
        }
        HttpRequest get = HttpUtil.createGet(url);
        HashMap<String, String> header = new HashMap<>();
        header.put("x-token",token);
        get.addHeaders(header);
        HashMap<String, Object> form = new HashMap<>();
        form.put("pageSize",pageSize);
        form.put("pageNumber",pageNum);
        form.put("returnTotalSize",1);
        get.form(form);
        System.out.println(form);
        HttpResponse execute = get.execute();
        System.out.println(execute.body());
        return JSONUtil.parseObj(execute.body());
    }
}
